<template>
  <div class="cart-container">
    <div class="header">
      <span class="title">购物车</span>
      <div class="actions">
        <button class="btn" @click="clearCart">清空</button>
      </div>
    </div>

    <div v-if="items.length === 0" class="empty">购物车还是空的</div>

    <div v-else class="list">
      <div class="item" v-for="it in items" :key="it.id">
        <img class="cover" :src="it.image_url" />
        <div class="info">
          <div class="name">{{ it.name }}</div>
          <div class="price">¥{{ it.price }}</div>
          <div class="qty">
            <button type="button" @click="dec(it)">-</button>
            <span class="num">{{ it.qty }}</span>
            <button type="button" @click="inc(it)">+</button>
          </div>
        </div>
        <button class="remove" @click="removeItem(it.id)">×</button>
      </div>
    </div>

    <div class="footer" v-if="items.length > 0">
      <div class="total">合计：<b>¥{{ total }}</b></div>
      <button class="checkout" @click="goCheckout">去结算</button>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'

const router = useRouter()
const items = ref([])

const load = () => {
  items.value = JSON.parse(localStorage.getItem('cart') || '[]')
}
const save = () => {
  localStorage.setItem('cart', JSON.stringify(items.value))
}
const removeItem = (id) => {
  items.value = items.value.filter(i => i.id !== id)
  save()
}
const clearCart = () => {
  items.value = []
  save()
}
const inc = (it) => {
  if (it.qty < it.stock) {
    it.qty += 1
    save()
  }
}
const dec = (it) => {
  if (it.qty > 1) {
    it.qty -= 1
    save()
  }
}
const total = computed(() => {
  return items.value.reduce((s, i) => s + Number(i.price) * i.qty, 0).toFixed(2)
})
const goCheckout = async () => {
  if (items.value.length === 0) return
  
  try {
    const token = localStorage.getItem('token')
    if (!token) {
      alert('请先登录再下单')
      router.push('/login')
      return
    }

    // 动态导入RabbitMQ版订单API，避免重复打包
    const { createOrder, convertCartToOrder, validateOrder } = await import('@/api/order-fixed')
    const orderData = convertCartToOrder(items.value)
    const validation = validateOrder(orderData)
    if (!validation.isValid) {
      alert('订单数据验证失败：\n' + validation.errors.join('\n'))
      return
    }
    
    console.log('🛒 购物车结算:', {
      items: items.value,
      orderData,
      total: total.value
    })
    
    const result = await createOrder(orderData)
    
    if (result.code === 200) {
      clearCart()
      alert(`订单创建成功！\n订单号：${result.data.order_no}\n状态：${result.data.status === 'pending' ? '处理中' : result.data.status}\n\n订单正在后台处理中，请稍后在订单页查看。`)
      router.push('/orders')
    } else {
      throw new Error(result.message || '订单创建失败')
    }
    
  } catch (error) {
    console.error('购物车结算失败:', error)
    alert(error.message || '下单失败，请稍后重试')
  }
}

onMounted(load)
</script>

<style scoped>
.cart-container { width:100vw; min-height:100vh; background:#f7f7f7; padding-bottom:70px; }
.header { position:sticky; top:0; background:#fff; padding:12px; display:flex; justify-content:space-between; align-items:center; border-bottom:1px solid #eee; z-index:5; }
.title { font-weight:700; }
.btn { border:1px solid #ddd; background:#fff; border-radius:6px; padding:6px 10px; }
.empty { padding:40px; text-align:center; color:#999; }
.list { padding:10px; display:flex; flex-direction:column; gap:10px; }
.item { display:flex; gap:10px; background:#fff; padding:10px; border-radius:8px; align-items:center; position:relative; }
.cover { width:80px; height:80px; object-fit:cover; background:#eee; border-radius:6px; }
.info { flex:1; }
.name { font-size:14px; font-weight:600; margin-bottom:6px; }
.price { color:#ff4757; font-weight:700; margin-bottom:6px; }
.qty { display:flex; align-items:center; gap:8px; }
.qty button { width:28px; height:28px; border:1px solid #ddd; background:#fff; border-radius:6px; }
.num { min-width:24px; text-align:center; }
.remove { position:absolute; right:10px; top:10px; border:none; background:#fff0f0; color:#ff4757; width:28px; height:28px; border-radius:6px; }
.footer { position:fixed; left:0; right:0; bottom:0; background:#fff; padding:10px; border-top:1px solid #eee; display:flex; align-items:center; justify-content:space-between; }
.checkout { background:#ff4757; color:#fff; border:none; border-radius:8px; padding:10px 16px; }
</style>


